package com.tdkj.util.typeconverter;

import java.lang.reflect.Member;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Map;

import com.opensymphony.xwork2.conversion.TypeConverter;

public class TimestampTypeConverter implements TypeConverter {
    
    public TimestampTypeConverter() {  
    }  
    
    public static final Timestamp convertToTimestamp(String dateString){
    	Timestamp timestamp = new Timestamp(DateTypeConverter.convertToDate(dateString).getTime());
    	return timestamp;
    }
    
    public static final DateFormat getDateFormat(String formatString) throws TypeConvertException {
    	return DateTypeConverter.getDateFormat(formatString);
    }
    
    public static final String convertToString(Timestamp time, String formatString) throws TypeConvertException {
    	return DateTypeConverter.getDateFormat(formatString).format(time);
    }

	@Override
	public Object convertValue(Map<String, Object> context, Object target,
			Member member, String propertyName, Object value, Class toType) {
		
		Object toObject = null;
    	
    	if(toType.equals(java.sql.Timestamp.class)){
    		
    		if(value instanceof String){
    			String dateString = String.valueOf(value);
    			Object obj = convertToTimestamp(dateString);
    			toObject = obj;
    		}else if(value instanceof String[]){
    			
    			String[] dateStrings = (String[])value;
    			if(dateStrings.length == 1 ){
    				Object obj = convertToTimestamp(dateStrings[0]);
	    			toObject = obj;
    			}else{
	    			Object[] objs = new Timestamp[dateStrings.length];
	    			for(int i=0; i<dateStrings.length; i++){
	    				objs[i] = convertToTimestamp(dateStrings[i]);
	    			}
	    			toObject = objs;
    			}
    		}
    	}else{
    		toObject = value;
    	}
    	
		return toObject;
	}
    


}
